// This file is part of OpenMeca, an easy software to do mechanical simulation.
//
// Author(s)    :  - Damien ANDRE  <openmeca@gmail.com>
//
// Copyright (C) 2012 Damien ANDRE
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.


#include <cassert>

#include "OpenMeca/Core/XmlConfigFile.hpp"
#include "OpenMeca/Core/ConfigDirectory.hpp"


namespace OpenMeca
{
  namespace Core
  {

    std::map<const std::string, XmlConfigFile*> XmlConfigFile::all_ = std::map<const std::string, XmlConfigFile*>();

    // QFile& 
    // XmlConfigFile::Open(const std::string name)
    // {
    //   assert(all_.count(name)<=1);
    //   if (all_.count(name)==0)
    // 	new XmlConfigFile(name);
    //   assert(all_.count(name)==1);
    //   return all_[name]->OpenFile();
    // }

    QDir 
    XmlConfigFile::GetConfigXmlFileDirectory()
    {
      QDir dir = ConfigDirectory::Get();
      
      if (dir.exists(GetDirectoryName().c_str())==false)
	assert(dir.mkdir(GetDirectoryName().c_str())==true);
	  
      assert(dir.cd(GetDirectoryName().c_str())==true);
      return dir;
    }

    std::string 
    XmlConfigFile::GetDirectoryName()
    {
      return std::string("Xml");
    }
    
    std::string 
    XmlConfigFile::GetSuffix()
    {
      return std::string(".xml");
    }


    XmlConfigFile::XmlConfigFile(const std::string name)
      :name_(name + GetSuffix()),
       file_(),
       backupFile_(":/" + QString(XmlConfigFile::GetDirectoryName().c_str()) + "/" + QString(name_.c_str()))
    {
      assert(backupFile_.exists());
      assert(QString(name_.c_str()).endsWith(QString(GetSuffix().c_str()))==true);
      assert(all_.count(name_)==0);
      all_[name_]=this;
    }

    XmlConfigFile::~XmlConfigFile()
    {
    }
    
    QFile&
    XmlConfigFile::Open()
    {
      file_.close();
      QDir dir = GetConfigXmlFileDirectory();
      
      const QString filePath = dir.absolutePath() + "/" + QString(name_.c_str());
      if (QFile::exists(filePath)==false)
	RestoreBackup();

      file_.setFileName(filePath);
      assert(file_.open(QIODevice::ReadOnly | QIODevice::Text)==true);
      return file_;

    }

    void 
    XmlConfigFile::RestoreBackup()
    {
      QDir dir = GetConfigXmlFileDirectory();
      const QString filePath = dir.absolutePath() + "/" + QString(name_.c_str());
      assert(backupFile_.copy(filePath));
    }


  }
}




